﻿using System;
using System.Collections.Generic;
using System.Data.SqlServerCe;
using System.IO;
using System.Linq;
using System.Text;
using NHibernate.Util;

namespace NHibernate.MsSqlCe
{
    public class NHibernateMsSqlCeDatabaseGenerator : NHibernateDatabaseGeneratorBase<NHibernateMsSqlCeDatabaseInfo>
    {
        static string DEFAULT_DATABASE_PATH = Directory.GetCurrentDirectory() + "\\" + "default.sdf";
        static NHibernateMsSqlCeDatabaseInfo DEFAULT_INFO = new NHibernateMsSqlCeDatabaseInfo()
        {
            DatabasePath = DEFAULT_DATABASE_PATH,
            Encrypted = false,
            Password = "",
            Properties = ConfigurationUtil.GetDefaultProperties(),
            Resources = null
        };

        public override Cfg.Configuration GetConfiguration(NHibernateMsSqlCeDatabaseInfo info)
        {
            return ConfigurationUtil.BuildMsSqlCeConfiguration(CreateConnectionString(info), info.Properties, info.Resources);
        }

        //NHibernateMsSqlCeDatabaseInfo _info;
        //public void SetDatabaseInfo(NHibernateMsSqlCeDatabaseInfo info)
        //{
        //    _info = info;
        //}

        protected override NHibernateMsSqlCeDatabaseInfo GetDatabaseInfo()
        {
            return _info ?? DEFAULT_INFO;
        }

        protected override void CreateEmptyDatabase(NHibernateMsSqlCeDatabaseInfo info)
        {
            SqlCeEngine engine = new SqlCeEngine(CreateConnectionString(info));
            engine.CreateDatabase();
        }

        private string CreateConnectionString(NHibernateMsSqlCeDatabaseInfo info)
        {
            return string.Format(@"Data Source={0}; File Mode=Exclusive; Encrypt={1}; Password={2};", info.DatabasePath, info.Encrypted, info.Password);
        }
    }
}
